Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve function declaration wrapping when it contains generic type definitions #4553

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Pedro-Muller29
Copy link

Description

This PR addresses #4071 by improving how Black wraps function definitions that include generic type declarations.

Current Behavior

When a function with generic type declarations is formatted, Black prioritizes wrapping the generic type definitions, even in cases where splitting the arguments would result in a cleaner layout. For example:

Input:

def func[T](a: T, b: T,) -> T:
    return a

Current Output:

def func[
    T
](a: T, b: T,) -> T:
    return a

New Behavior

With this improvement, Black prioritizes wrapping the arguments instead of the generic type definitions, resulting in more readable code:

Improved Output:

def func[T](
    a: T,
    b: T,
) -> T:
    return a

However, Black will still wrap the generic type declarations if:

  1. A magic trailing comma is present in the generic type declaration.
  2. The length of the line from the start of the function declaration to the closing square bracket approaches the line limit, making necessary wrapping it to conform to the limit.

For example:

Input:

def trailing_comma1[T=int,](a: str):
    pass

Output:

def trailing_comma1[
    T = int,
](a: str):
    pass

Implementation details:

In the left_hand_split function, black would search for an opening brackets leaf in function declaration. It was not differentiating between squared brackets and parenthesis, thus it was treating function parameters and generic type definitions the same way. Since generic type definitions comes first, it would always wrap them first.

The solution was to just make it ignore the opening of square brackets in all cases, expect:

  1. There was a magic trailing comma in the generic type definition.
  2. If the amount of characters from the start of the function declaration until the closing squared bracket would almost reach the line limit.

Checklist

  • Added an entry in CHANGES.md if necessary.
  • Added/updated tests to cover the changes.
  • Updated documentation as needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant